package com.hrp.book.ui.search

import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils
import com.hrp.book.R
import com.hrp.book.adapter.SearchBookAdapter
import com.hrp.book.base.BaseFragment
import com.hrp.book.databinding.FragmentSearchBinding
import kotlinx.coroutines.launch

class SearchFragment : BaseFragment<FragmentSearchBinding, SearchModel>() {

    companion object {
        fun newInstance(): SearchFragment {
            val args = Bundle()

            val fragment = SearchFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private val searchAdapter: SearchBookAdapter by lazy {
        SearchBookAdapter()
    }

    override fun onLazyInitView(savedInstanceState: Bundle?) {
        super.onLazyInitView(savedInstanceState)
        binding.fragment = this
        binding.bookList.adapter = searchAdapter
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_search
    }


    override fun pop() {
        hideSoftInput()
        super.pop()
    }


    fun onEditorAction(textView: TextView, actionId: Int, keyEvent: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            search(binding.tvSearch)
            hideSoftInput()
            return true
        }
        return false
    }

    fun search(view: View) {
        view as TextView
        hideSoftInput()
        binding.edSearch.clearFocus()
        lifecycleScope.launch {
            val books = viewModel.search(binding.edSearch.text.toString())
            LogUtils.e("test_", books.size)
            searchAdapter.setNewInstance(books)
        }
    }
}